package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.dto.pyq.FeedMedia;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.RegularUtil;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.EmojiUtil;
import com.uzai.console.common.utils.MsgSplitUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.pyq.DeletePyqDto;
import com.uzai.console.dto.feign.pyq.SendPyqDto;
import com.uzai.console.dto.feign.turnlink.GenerateShortUrlDto;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.pyq.pyqjobdetail.*;
import com.uzai.console.dto.pyq.pyqmaterial.TurnlinkDto;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.PyqJobDetail;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiBusinessFeignService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.feign.dto.GoodsUpdateExposureNumBySendPyqDto;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.pyq.PyqJobDetailService;
import com.uzai.console.service.pyq.PyqMaterialService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.vo.cms.base.CmsBaseInfoVo;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.lly.LlyMiddleDetail;
import com.uzai.console.vo.pyq.pyqjobdetail.PyqJobDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 朋友圈明细
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqJobDetailServiceImpl implements PyqJobDetailService {

    Logger logger = LoggerFactory.getLogger(PyqJobDetailServiceImpl.class);

    @Autowired
    private PyqJobMapper pyqJobMapper;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private PyqMaterialService pyqMaterialService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private PyqCommentTemplateMapper pyqCommentTemplateMapper;
    @Autowired
    private PyqExpressionMapper pyqExpressionMapper;
    @Autowired
    private SysDomainMapper sysDomainMapper;
    @Autowired
    private PyqLlyGoodsMapper pyqLlyGoodsMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private PyqLlyShortlinkMapper pyqLlyShortlinkMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    /**
     * 查询朋友圈明细列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailQuery
     * @return null
     */
    public Page<PyqJobDetailVo> findPyqJobDetailList(PyqJobDetailQuery pyqJobDetailQuery){
        //新建返回到页面的LIST对象
        List<PyqJobDetailVo> pyqJobDetailVoList = new ArrayList<>();

        //执行分页查询对象
        Page<PyqJobDetailVo> page = new Page<>();
        pyqJobDetailQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(pyqJobDetailQuery.getMerId())));

        //发送任务id
        if(pyqJobDetailQuery.getJobId() != null){
            boolQuery.must(QueryBuilders.termQuery("jobId",pyqJobDetailQuery.getJobId()));
        }

        //状态
        if(pyqJobDetailQuery.getStatus() != null){
            boolQuery.must(QueryBuilders.termQuery("status",pyqJobDetailQuery.getStatus()));
        }

        //机器人唯一id
        if(pyqJobDetailQuery.getDeviceUniqueId() != null){
            boolQuery.must(QueryBuilders.termQuery("deviceUniqueId",pyqJobDetailQuery.getDeviceUniqueId()));
        }

        if(pyqJobDetailQuery.getComplete() != null){
            if(pyqJobDetailQuery.getComplete().intValue() == 1){ //发送完成
                boolQuery.must(QueryBuilders.rangeQuery("status").gte(3));
            }
        }

        //发送开始时间
        if(pyqJobDetailQuery.getQueryStartTime() != null){
            boolQuery.must(QueryBuilders.rangeQuery("sendTime").gte(pyqJobDetailQuery.getQueryStartTime()));
        }

        //发送结束时间
        if(pyqJobDetailQuery.getQueryEndTime() != null){
            boolQuery.must(QueryBuilders.rangeQuery("sendTime").lte(pyqJobDetailQuery.getQueryEndTime()));
        }

        //内容
        if(StringUtils.isNotBlank(pyqJobDetailQuery.getContent())){
            boolQuery.must(QueryBuilders.matchQuery("content", pyqJobDetailQuery.getContent()));
        }

        //评论
        if(StringUtils.isNotBlank(pyqJobDetailQuery.getCommentContent())){
            boolQuery.must(QueryBuilders.matchQuery("commentContent", pyqJobDetailQuery.getCommentContent()));
        }

        //商品id尾部
        if(StringUtils.isNotBlank(pyqJobDetailQuery.getItemTailId())){
            boolQuery.must(QueryBuilders.termQuery("itemTailId.keyword",pyqJobDetailQuery.getItemTailId()));
        }

        //发送来源（0手动发送；1自动发圈；2自动跟发）
        if(pyqJobDetailQuery.getSource() != null){
            boolQuery.must(QueryBuilders.termQuery("source",pyqJobDetailQuery.getSource()));
        }

        //朋友圈类型 0商品 1图文 2悠哉精选(淘宝) 3悠哉精选(拼多多) 10悠友圈
        if(pyqJobDetailQuery.getType() != null){
            boolQuery.must(QueryBuilders.termQuery("type",pyqJobDetailQuery.getType()));
        }

        //朋友圈附件类型
        if(pyqJobDetailQuery.getAttachType() != null){
            boolQuery.must(QueryBuilders.termQuery("attachType",pyqJobDetailQuery.getAttachType()));
        }

        searchSourceBuilder.query(boolQuery);
        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetailQuery.getMerId());


        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_pyq_job_detail, searchSourceBuilder, pyqJobDetailQuery.getSize(), pyqJobDetailQuery.getFromIndex(), null, null, null, pyqJobDetailQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                PyqJobDetail pyqJobDetail  = JSONObject.parseObject(JSONObject.toJSONString(dataMp), PyqJobDetail.class);
                PyqJobDetailVo pyqJobDetailVo = new PyqJobDetailVo();
                if(pyqJobDetail != null){
                    BeanUtils.copyProperties(pyqJobDetail, pyqJobDetailVo);
                    if(pyqJobDetailVo.getDeviceUniqueId() != null){
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(pyqJobDetailVo.getDeviceUniqueId(), DeviceTypeEnum.getById(pyqJobDetail.getDeviceType()).getKey(), pyqJobDetail.getMerId());
                        if(device != null){
                            DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                            BeanUtils.copyProperties(device, deviceInfoVo);
                            pyqJobDetailVo.setDeviceInfoVo(deviceInfoVo);
                        }
                    }

                    //朋友圈类型
                    if(pyqJobDetailVo.getAttachType() != null){
                        AttachTypeEnum attachTypeEnum = AttachTypeEnum.getById(pyqJobDetailVo.getAttachType());
                        if(attachTypeEnum != null){
                            pyqJobDetailVo.setAttachTypeName(attachTypeEnum.getDesc());
                        }
                    }

                    //封装图片
                    if(StringUtils.isNotBlank(pyqJobDetailVo.getFeedMediaList())){
                        List<FeedMedia> feedMediaList = JSONObject.parseArray(pyqJobDetailVo.getFeedMediaList(), FeedMedia.class);
                        if(feedMediaList != null && feedMediaList.size() > 0){
                            List<String> imgList = new ArrayList<>();
                            if(Tools.getInteger(pyqJobDetailVo.getAttachType()).intValue() == 2){
                                for (FeedMedia feedMedia : feedMediaList) {
                                    imgList.add(feedMedia.getUrl());
                                }
                            }else{
                                for (FeedMedia feedMedia : feedMediaList) {
                                    imgList.add(feedMedia.getCover());
                                }
                            }
                            pyqJobDetailVo.setImgs(JSONObject.toJSONString(imgList));
                        }
                    }else{ //旧版接口
                        if(StringUtils.isNotBlank(pyqJobDetailVo.getImgs())){
                            List<String> imgList = JSONObject.parseArray(pyqJobDetailVo.getImgs(), String.class);
                            pyqJobDetailVo.setImgs(JSONObject.toJSONString(imgList));
                        }
                    }

                    //视频号朋友圈，如果图片为空，封装首图
                    if(StringUtils.isBlank(pyqJobDetailVo.getImgs())){
                        if(AttachTypeEnum.SHIPINHAO.getValue().intValue() == Tools.getInteger(pyqJobDetailVo.getAttachType()).intValue()){
                            List<String> imgList = new ArrayList<>();
                            imgList.add(Const.PyqFirstImg.SHIPINHAO);
                            pyqJobDetailVo.setImgs(JSONObject.toJSONString(imgList));
                        }
                    }

                    pyqJobDetailVoList.add(pyqJobDetailVo);
                }
            }
        }

        //返回到页面分页对象
        page.setRecords(pyqJobDetailVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 查询朋友圈明细详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailIdDto
     * @return null
     */
    public PyqJobDetailVo findPyqJobDetail(PyqJobDetailIdDto pyqJobDetailIdDto){
        PyqJobDetailVo pyqJobDetailVo = new PyqJobDetailVo();
        if(pyqJobDetailIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetailIdDto.getMerId());

        Map<String,Object> pyqJobDetailEsMap = elasticsearchUtilGroupMsg.searchDataById(uzai_pyq_job_detail, String.valueOf(pyqJobDetailIdDto.getId()), null);
        PyqJobDetail pyqJobDetail = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pyqJobDetailEsMap)), PyqJobDetail.class);
        if(pyqJobDetail != null){
            BeanUtils.copyProperties(pyqJobDetail, pyqJobDetailVo);
            if(pyqJobDetail.getDeviceUniqueId() != null){
                Device device = deviceService.findDeviceInfoByDeviceUniqueId(pyqJobDetailVo.getDeviceUniqueId(), DeviceTypeEnum.getById(pyqJobDetail.getDeviceType()).getKey() ,pyqJobDetail.getMerId());
                if(device != null){
                    DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                    BeanUtils.copyProperties(device, deviceInfoVo);
                    pyqJobDetailVo.setDeviceInfoVo(deviceInfoVo);
                }
            }

            //朋友圈类型
            if(pyqJobDetailVo.getAttachType() != null){
                AttachTypeEnum attachTypeEnum = AttachTypeEnum.getById(pyqJobDetailVo.getAttachType());
                if(attachTypeEnum != null){
                    pyqJobDetailVo.setAttachTypeName(attachTypeEnum.getDesc());
                }
            }

            //封装图片
            if(StringUtils.isNotBlank(pyqJobDetail.getFeedMediaList())){
                List<FeedMedia> feedMediaList = JSONObject.parseArray(pyqJobDetailVo.getFeedMediaList(), FeedMedia.class);
                if(feedMediaList != null && feedMediaList.size() > 0){
                    List<String> imgList = new ArrayList<>();
                    if(Tools.getInteger(pyqJobDetail.getAttachType()).intValue() == 2){
                        for (FeedMedia feedMedia : feedMediaList) {
                            imgList.add(feedMedia.getUrl());
                        }
                    }else{
                        for (FeedMedia feedMedia : feedMediaList) {
                            imgList.add(feedMedia.getCover());
                        }
                    }
                    pyqJobDetailVo.setImgs(JSONObject.toJSONString(imgList));
                }
            }else{ //旧版接口
                if(StringUtils.isNotBlank(pyqJobDetailVo.getImgs())){
                    List<String> imgList = JSONObject.parseArray(pyqJobDetailVo.getImgs(), String.class);
                    pyqJobDetailVo.setImgs(JSONObject.toJSONString(imgList));
                }
            }
        }

        return pyqJobDetailVo;
    }

    /**
     * 再发一次
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailIdDto
     * @return null
     */
    public void sendBegin(PyqJobDetailIdDto pyqJobDetailIdDto){

        if(pyqJobDetailIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择明细id");
        }

        //先查询该朋友圈明细
        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetailIdDto.getMerId());

        Map<String,Object> pyqJobDetailEsMap = elasticsearchUtilGroupMsg.searchDataById(uzai_pyq_job_detail, String.valueOf(pyqJobDetailIdDto.getId()), null);
        PyqJobDetail pyqJobDetail = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pyqJobDetailEsMap)), PyqJobDetail.class);

        if(pyqJobDetail == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该朋友圈明细不存在");
        }

        //主键id
        Long id = IdWorker.getId();
        Integer now = DateUtil.getNowTime();
        pyqJobDetail.setId(String.valueOf(id));
        pyqJobDetail.setCreateTime(now);
        pyqJobDetail.setUpdateTime(now);
        pyqJobDetail.setStatus(PyqJobStatusEnum.SENDING.getValue()); //发送中
        pyqJobDetail.setPyqId(null);

        elasticsearchUtilGroupMsg.addData(JSONObject.parseObject(JSONObject.toJSONString(pyqJobDetail)), uzai_pyq_job_detail, pyqJobDetail.getId());

        //修改发送任务, 增加发送总数
        if(pyqJobDetail.getJobId() != null){
            PyqJob pyqJob = pyqJobMapper.selectById(pyqJobDetail.getJobId(), pyqJobDetail.getMerId());
            if(pyqJob != null){
                pyqJob.setTotalCount(pyqJob.getTotalCount() + 1);
                pyqJobMapper.updateById(pyqJob);
            }
        }

        //发送再发一次接口
        SendPyqDto sendPyqDto = new SendPyqDto();
        sendPyqDto.setId(String.valueOf(id));
        sendPyqDto.setMerId(pyqJobDetailIdDto.getMerId());
        int time1 = DateUtil.getNowTime();
        UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.sendPyqById(sendPyqDto);
        int time2 = DateUtil.getNowTime();
        logger.info("----再发一次微信朋友圈---usetime={}, id={}, result={}",time2-time1, id, JSONObject.toJSONString(uzaiRespVo));

    }


    /**
     * 立即发送
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailIdDto
     * @return null
     */
    public void sendNow(PyqJobDetailIdDto pyqJobDetailIdDto){
        if(pyqJobDetailIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择明细id");
        }
        //再次发送
        SendPyqDto sendPyqDto = new SendPyqDto();
        sendPyqDto.setId(pyqJobDetailIdDto.getId());
        sendPyqDto.setMerId(pyqJobDetailIdDto.getMerId());
        int time1 = DateUtil.getNowTime();
        UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.sendPyqById(sendPyqDto);
        int time2 = DateUtil.getNowTime();
        logger.info("----立即发送微信朋友圈---usetime={}, id={}, result={}",time2-time1, pyqJobDetailIdDto.getId(), JSONObject.toJSONString(uzaiRespVo));

    }

    /**
     * 删除微信朋友圈-不删明细
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailDeleteDto
     * @return null
     */
    public void deleteWxPyq(PyqJobDetailDeleteDto pyqJobDetailDeleteDto){
        if(pyqJobDetailDeleteDto.getId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择明细id");
        }

        if(pyqJobDetailDeleteDto.getPyqId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选输入朋友圈id");
        }

        //删除朋友圈
        DeletePyqDto deletePyqDto = new DeletePyqDto();
        deletePyqDto.setId(pyqJobDetailDeleteDto.getId());
        deletePyqDto.setPyqId(pyqJobDetailDeleteDto.getPyqId());
        deletePyqDto.setMerId(pyqJobDetailDeleteDto.getMerId());

        int time1 = DateUtil.getNowTime();
        UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.deletePyq(deletePyqDto);
        int time2 = DateUtil.getNowTime();
        logger.info("----删除微信朋友圈---usetime={}, pyqId={}, result={}",time2-time1, pyqJobDetailDeleteDto.getPyqId(), JSONObject.toJSONString(uzaiRespVo));

        //修改明细状态
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", PyqJobDetailStatusEnum.DELPYQ.getValue()); //删除朋友圈
        jsonObject.put("updateTime", DateUtil.getNowTime());

        //先查询该朋友圈明细
        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetailDeleteDto.getMerId());

        elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_pyq_job_detail, pyqJobDetailDeleteDto.getId());
    }

    /**
     * 停止发送
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailIdDto
     * @return null
     */
    public void stopPyqJobDetail(PyqJobDetailIdDto pyqJobDetailIdDto){
        if(pyqJobDetailIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择明细id");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", PyqJobStatusEnum.SUSPEND.getValue()); //暂停
        jsonObject.put("updateTime", DateUtil.getNowTime());
        //先查询该朋友圈明细
        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetailIdDto.getMerId());

        elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_pyq_job_detail, pyqJobDetailIdDto.getId());
        try {
            Thread.sleep(500);
        }catch (Exception e){

        }
    }

    /**
     * 发送朋友圈
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param pyqJob
     * @return null
     */
    @Override
    public PyqJobDetail  sendPyqJobDetailSync(PyqJob pyqJob, Long deviceUniqueId, Long middlePageDomainId){
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, pyqJob.getDeviceType(), pyqJob.getMerId());
        if(device == null){
            return null;
        }
        PyqJobDetail pyqJobDetail = new PyqJobDetail() ;
        pyqJobDetail.setId(String.valueOf(IdWorker.getId()));
        pyqJobDetail.setVersion(0L);
        pyqJobDetail.setMerId(pyqJob.getMerId());
        pyqJobDetail.setJobId(pyqJob.getId());
        pyqJobDetail.setStatus(PyqJobDetailStatusEnum.NOSEND.getValue());
        pyqJobDetail.setDeviceUniqueId(deviceUniqueId);
        pyqJobDetail.setDeviceType(device.getRecvmsgType());
        pyqJobDetail.setType(pyqJob.getType());
        pyqJobDetail.setPlatform(pyqJob.getPlatform());
        pyqJobDetail.setSource(pyqJob.getSource());//发送来源（0手动发送；1自动发圈；2自动跟发）
        pyqJobDetail.setItemId(pyqJob.getItemId());
        pyqJobDetail.setItemHeaderId(pyqJob.getItemHeaderId());
        pyqJobDetail.setItemTailId(pyqJob.getItemTailId());
        pyqJobDetail.setCouponId(pyqJob.getCouponId());
        pyqJobDetail.setCouponVal(pyqJob.getCouponVal());
        pyqJobDetail.setFinalPrice(pyqJob.getFinalPrice());
        pyqJobDetail.setStartTime(pyqJob.getSendTime());

        //2023-08-23 修改增加媒体信息
        pyqJobDetail.setImgs(null);
        pyqJobDetail.setFeedMediaList(pyqJob.getFeedMedia());
        pyqJobDetail.setAttachType(pyqJob.getAttachType());
        pyqJobDetail.setPyqVideoNumber(pyqJob.getVideoNumber());

        Integer now = DateUtil.getNowTime();
        pyqJobDetail.setCreateTime(now);
        pyqJobDetail.setUpdateTime(now);
        //朋友圈内容
        String content = Tools.getStr(pyqJob.getContent());
        //替换随机表情
        while (content.contains("[随机表情]")){
            content = content.replaceFirst("\\[随机表情\\]", Tools.getStr(EmojiUtil.getRandomEmoji()));
        }
        //替换随机字符串
        content = MsgSplitUtil.replaceRandomStrArgs(content);
        pyqJobDetail.setContent(content);

        String commentContent = Tools.getStr(pyqJob.getCommentContent());
        //替换随机表情
        while (commentContent.contains("[随机表情]")){
            commentContent = commentContent.replaceFirst("\\[随机表情\\]", Tools.getStr(EmojiUtil.getRandomEmoji()));
        }
        //替换随机字符串
        commentContent = MsgSplitUtil.replaceRandomStrArgs(commentContent);
        pyqJobDetail.setCommentContent(commentContent);

        if(pyqJob.getType() != null){
            if(pyqJob.getType().intValue() == 0 || pyqJob.getType().intValue() == 2 || pyqJob.getType().intValue() == 3){ //商品或者老林云商品
                //判断是否有今日合集变量，如果有，则商品的购买连接url地址也需要拼接今日合集参数
                boolean todaySendListFlag = false;
                if(content.contains("[今日合集]") || commentContent.contains("[今日合集]")){
                    todaySendListFlag = true; //有今日合集
                    //CMS配置域名
                    String cmsDomain = "";
                    Long mailDomain = Tools.getLong(middlePageDomainId);
                    if(mailDomain.longValue() == 0){ //官方域名
                        SysDomain sysDomain = sysDomainMapper.selectById(2L, 1L);
                        if(sysDomain != null){
                            cmsDomain = Tools.getStr(sysDomain.getSiteDomain());
                        }
                    }else{
                        SysDomain sysDomain = sysDomainMapper.selectById(mailDomain, pyqJob.getMerId());
                        if(sysDomain != null){
                            cmsDomain = Tools.getStr(sysDomain.getSiteDomain());
                        }
                    }

                    if(StringUtils.isBlank(cmsDomain)){ //官方域名
                        logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                                pyqJob.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                "",0L,
                                "设备方案未配置域名")));

                        //默认发送失败
                        pyqJobDetail.setStatus(PyqJobDetailStatusEnum.SENDFAIL.getValue());
                        pyqJobDetail.setFailMsg("设备方案未配置域名");
                        return pyqJobDetail;
                    }

                    //今日合集访问地址
                    String middPageUrl = cmsDomain + "/" + uzaiConsoleSysConfig.getPyqTodaySendListUrl();
                    //替换朋友圈明细id和运营商id
                    middPageUrl = String.format(middPageUrl, pyqJobDetail.getId(), pyqJobDetail.getMerId());
                    //生成短链接
                    GenerateShortUrlDto generateShortUrlDto = new GenerateShortUrlDto();
                    generateShortUrlDto.setMerId(pyqJob.getMerId());
                    generateShortUrlDto.setUrl(middPageUrl);
                    generateShortUrlDto.setIgnoreShortUrlAuth(1);//忽略权限，不收费
                    generateShortUrlDto.setMiddlePageDomainId(middlePageDomainId);
                    UzaiRespVo<String> uzaiRespVo = uzaiTurnlinkFeignService.generateShortUrl(generateShortUrlDto);
                    logger.info("---发送朋友圈[今日合集]访问地址转成短链接---dto={},result={}",JSONObject.toJSONString(generateShortUrlDto), JSONObject.toJSONString(uzaiRespVo));
                    if(uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                        //获取生成的短链接
                        middPageUrl = uzaiRespVo.getData();
                        //短链接为空，则不替换[今日合集]
                        if (StringUtils.isNotBlank(middPageUrl)) {
                            content = content.replace("[今日合集]", middPageUrl);
                            commentContent = commentContent.replace("[今日合集]", middPageUrl);
                        }else{
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                                    pyqJob.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                    "",0L,
                                    "发送朋友圈，[今日合集]变量访问地址转成短链接失败！")));
                        }
                    }
                }

                //判断是否有今日合集变量，如果有，则购买连接需要拼今日合集参数-修改成不管咋样都需要今日合集
                //if(todaySendListFlag){
                if(true) {
                    //先转链-不生成短链接
                    TurnlinkDto turnlinkDto = new TurnlinkDto();
                    turnlinkDto.setMerId(pyqJob.getMerId());
                    turnlinkDto.setPlatform(pyqJob.getPlatform());
                    turnlinkDto.setCouponId(pyqJob.getCouponId());
                    turnlinkDto.setDeviceUniqueId(deviceUniqueId);
                    turnlinkDto.setDevicePlanId(pyqJob.getDevicePlanId());
                    turnlinkDto.setItemId(pyqJob.getItemId());
                    if (StringUtils.isNotBlank(pyqJob.getItemUrl())) {
                        turnlinkDto.setUrl(pyqJob.getItemUrl());
                    }
                    turnlinkDto.setGenerateShortUrl(0);//不生成短链接，拼凑今日合集参数之后在生成短链接
                    //老林商品库忽略短链接授权
                    if (pyqJob.getType().intValue() == 2) {
                        turnlinkDto.setIgnoreShortUrlAuth(1);//忽略，不收费
                    }
                    SimpleTurnlinkVo simpleTurnlinkVo = getGoodInfo(turnlinkDto);
                    //判断是否有购买链接和淘口令，如果没有，则不发朋友圈
                    if (StringUtils.isBlank(simpleTurnlinkVo.getBuyUrl())) {
                        logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                                pyqJob.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                "", 0L,
                                "转链失败,未获取到购买链接")));

                        pyqJobDetail.setStatus(PyqJobDetailStatusEnum.SENDFAIL.getValue());
                        if(StringUtils.isNotBlank(simpleTurnlinkVo.getReturnMsg())){
                            pyqJobDetail.setFailMsg(simpleTurnlinkVo.getReturnMsg());
                        }else{
                            pyqJobDetail.setFailMsg("转链失败,未获取到购买链接");
                        }

                        return pyqJobDetail;
                    }

                    //设置淘口令
                    pyqJobDetail.setItemPwd(simpleTurnlinkVo.getBuyPwd());
                    //设置打开淘宝url
                    pyqJobDetail.setPwdShortUrl(simpleTurnlinkVo.getPwdShortUrl());

                    if (Tools.getInteger(pyqJobDetail.getPlatform()).intValue() == 0) { //淘宝

                        //购买连接此时为长连接，需要拼接朋友圈id参数，在申请短链接
                        String buyUrl = simpleTurnlinkVo.getBuyUrl();

                        //拼接今日合集参数
                        buyUrl = buyUrl + String.format(uzaiConsoleSysConfig.getPyqBuyUrlAddTodaySendListPara(), pyqJobDetail.getId(), pyqJobDetail.getMerId());
                        //拼接今日合集参数之后的购买链接生成短链接
                        GenerateShortUrlDto generateShortUrlDto = new GenerateShortUrlDto();
                        generateShortUrlDto.setMerId(pyqJob.getMerId());
                        generateShortUrlDto.setUrl(buyUrl);
                        generateShortUrlDto.setIgnoreShortUrlAuth(1);//忽略生成短链接权限，不收费
                        UzaiRespVo<String> uzaiRespVo = uzaiTurnlinkFeignService.generateShortUrl(generateShortUrlDto);
                        logger.info("---拼接朋友圈商品长连接申请短链接接口--para={},reuslt={}", JSONObject.toJSONString(generateShortUrlDto), JSONObject.toJSONString(uzaiRespVo));
                        //申请短链接成功，则替换购买连接和淘口令
                        if (uzaiRespVo != null && uzaiRespVo.getCode() == 200 && StringUtils.isNotBlank(uzaiRespVo.getData())) {
                            String shortBuyUrl = Tools.getStr(uzaiRespVo.getData());
                            content = content.replace("[购买链接]", shortBuyUrl)
                                    .replace("[淘口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()));
                            pyqJobDetail.setContent(content);

                            //评论内容替换变量
                            commentContent = commentContent.replace("[购买链接]", shortBuyUrl)
                                    .replace("[淘口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()));
                            pyqJobDetail.setCommentContent(commentContent);
                        } else {//申请短链接失败
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                                    pyqJob.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                    "", 0L,
                                    "未获取到短链接")));
                            pyqJobDetail.setStatus(PyqJobDetailStatusEnum.SENDFAIL.getValue());
                            pyqJobDetail.setFailMsg("转链失败,未获取到短链接");
                            return pyqJobDetail;
                        }
                    }else if(Tools.getInteger(pyqJobDetail.getPlatform()).intValue() == 4){ //抖音
                        //购买连接此时为长连接，需要拼接朋友圈id参数，再申请短链接
                        String buyUrl = simpleTurnlinkVo.getBuyUrl();

                        //拼接今日合集参数
                        buyUrl = buyUrl + String.format(uzaiConsoleSysConfig.getPyqBuyUrlAddTodaySendListPara(), pyqJobDetail.getId(), pyqJobDetail.getMerId());
                        //拼接今日合集参数之后的购买链接生成短链接
                        GenerateShortUrlDto generateShortUrlDto = new GenerateShortUrlDto();
                        generateShortUrlDto.setMerId(pyqJob.getMerId());
                        generateShortUrlDto.setUrl(buyUrl);
                        generateShortUrlDto.setIgnoreShortUrlAuth(1);//忽略生成短链接权限，不收费
                        UzaiRespVo<String> uzaiRespVo = uzaiTurnlinkFeignService.generateShortUrl(generateShortUrlDto);
                        logger.info("---拼接朋友圈商品长连接申请短链接接口--para={},reuslt={}", JSONObject.toJSONString(generateShortUrlDto), JSONObject.toJSONString(uzaiRespVo));
                        //申请短链接成功，则替换购买连接和抖音口令
                        if (uzaiRespVo != null && uzaiRespVo.getCode() == 200 && StringUtils.isNotBlank(uzaiRespVo.getData())) {
                            String shortBuyUrl = Tools.getStr(uzaiRespVo.getData());
                            content = content.replace("[购买链接]", shortBuyUrl)
                                    .replace("[抖音口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()));
                            pyqJobDetail.setContent(content);

                            //评论内容替换变量
                            commentContent = commentContent.replace("[购买链接]", shortBuyUrl)
                                    .replace("[抖音口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()));
                            pyqJobDetail.setCommentContent(commentContent);
                        } else {//申请短链接失败
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                                    pyqJob.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                    "", 0L,
                                    "未获取到短链接")));

                            pyqJobDetail.setStatus(PyqJobDetailStatusEnum.SENDFAIL.getValue());
                            pyqJobDetail.setFailMsg("转链失败,未获取到短链接");
                            return pyqJobDetail;
                        }
                    }else if(Tools.getInteger(pyqJobDetail.getPlatform()).intValue() == 5){ //快手
                        //购买连接此时为长连接，需要拼接朋友圈id参数，再申请短链接
                        String buyUrl = simpleTurnlinkVo.getBuyUrl();

                        //拼接今日合集参数
                        buyUrl = buyUrl + String.format(uzaiConsoleSysConfig.getPyqBuyUrlAddTodaySendListPara(), pyqJobDetail.getId(), pyqJobDetail.getMerId());
                        //拼接今日合集参数之后的购买链接生成短链接
                        GenerateShortUrlDto generateShortUrlDto = new GenerateShortUrlDto();
                        generateShortUrlDto.setMerId(pyqJob.getMerId());
                        generateShortUrlDto.setUrl(buyUrl);
                        generateShortUrlDto.setIgnoreShortUrlAuth(1);//忽略生成短链接权限，不收费
                        UzaiRespVo<String> uzaiRespVo = uzaiTurnlinkFeignService.generateShortUrl(generateShortUrlDto);
                        logger.info("---拼接朋友圈商品长连接申请短链接接口--para={},reuslt={}", JSONObject.toJSONString(generateShortUrlDto), JSONObject.toJSONString(uzaiRespVo));
                        //申请短链接成功，则替换购买连接和抖音口令
                        if (uzaiRespVo != null && uzaiRespVo.getCode() == 200 && StringUtils.isNotBlank(uzaiRespVo.getData())) {
                            String shortBuyUrl = Tools.getStr(uzaiRespVo.getData());
                            content = content.replace("[购买链接]", shortBuyUrl)
                                    .replace("[快口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()));
                            pyqJobDetail.setContent(content);

                            //评论内容替换变量
                            commentContent = commentContent.replace("[购买链接]", shortBuyUrl)
                                    .replace("[快口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()));
                            pyqJobDetail.setCommentContent(commentContent);
                        } else {//申请短链接失败
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                                    pyqJob.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                    "", 0L,
                                    "未获取到短链接")));

                            pyqJobDetail.setStatus(PyqJobDetailStatusEnum.SENDFAIL.getValue());
                            pyqJobDetail.setFailMsg("转链失败,未获取到短链接");
                            return pyqJobDetail;
                        }
                    }else{//其他商品
                        String shortBuyUrl = Tools.getStr(simpleTurnlinkVo.getBuyUrl());
                        content = content.replace("[购买链接]",shortBuyUrl);
                        pyqJobDetail.setContent(content);

                        //评论内容替换变量
                        commentContent = commentContent.replace("[购买链接]", shortBuyUrl);
                        pyqJobDetail.setCommentContent(commentContent);
                    }
                }else{//没有今日合集变量，则正常转链
                    //先转链-生成短链接
                    TurnlinkDto turnlinkDto = new TurnlinkDto();
                    turnlinkDto.setMerId(pyqJob.getMerId());
                    turnlinkDto.setPlatform(pyqJob.getPlatform());
                    turnlinkDto.setCouponId(pyqJob.getCouponId());
                    turnlinkDto.setDevicePlanId(pyqJob.getDevicePlanId());
                    turnlinkDto.setItemId(pyqJob.getItemId());
                    if(StringUtils.isNotBlank(pyqJob.getItemUrl())){
                        turnlinkDto.setUrl(pyqJob.getItemUrl());
                    }
                    turnlinkDto.setDeviceUniqueId(deviceUniqueId);
                    turnlinkDto.setGenerateShortUrl(1);//生成短链接
                    //老林商品库忽略短链接授权
                    if(pyqJob.getType().intValue() == 2){
                        turnlinkDto.setIgnoreShortUrlAuth(1);//忽略，不收费
                    }
                    SimpleTurnlinkVo simpleTurnlinkVo = getGoodInfo(turnlinkDto);

                    //判断是否有购买链接和淘口令，如果没有，则不发朋友圈
                    if(StringUtils.isBlank(simpleTurnlinkVo.getBuyUrl())){
                        logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                                pyqJob.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                                "",0L,
                                "转链失败,未获取到购买链接")));

                        pyqJobDetail.setStatus(PyqJobDetailStatusEnum.SENDFAIL.getValue());
                        if(StringUtils.isNotBlank(simpleTurnlinkVo.getReturnMsg())){
                            pyqJobDetail.setFailMsg(simpleTurnlinkVo.getReturnMsg());
                        }else{
                            pyqJobDetail.setFailMsg("转链失败,未获取到购买链接");
                        }
                        return pyqJobDetail;
                    }

                    //设置淘口令
                    pyqJobDetail.setItemPwd(simpleTurnlinkVo.getBuyPwd());
                    //设置打开淘宝url
                    pyqJobDetail.setPwdShortUrl(simpleTurnlinkVo.getPwdShortUrl());

                    content = content.replace("[购买链接]",Tools.getStr(simpleTurnlinkVo.getBuyUrl()))
                            .replace("[淘口令]",Tools.getStr(simpleTurnlinkVo.getBuyPwd()))
                            .replace("[抖音口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()))
                            .replace("[快口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()));
                    pyqJobDetail.setContent(content);

                    //评论内容替换变量
                    commentContent = commentContent.replace("[购买链接]",Tools.getStr(simpleTurnlinkVo.getBuyUrl()))
                            .replace("[淘口令]",Tools.getStr(simpleTurnlinkVo.getBuyPwd()))
                            .replace("[抖音口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()))
                            .replace("[快口令]", Tools.getStr(simpleTurnlinkVo.getBuyPwd()));
                    pyqJobDetail.setCommentContent(commentContent);
                }

            }
//            else if(pyqJob.getType().intValue() == 2){ //老林云商品链接

                //modify by 2023-01-03,老林云商品从推老板商品库里查询，故老林云商品屏蔽
//                if(1==2){
//                    //CMS配置域名
//                    String cmsDomain = "";
//                    Long mailDomain = Tools.getLong(middlePageDomainId);
//                    if(mailDomain.longValue() == 0){ //官方域名
//                        SysDomain sysDomain = sysDomainMapper.selectById(2L, 1L);
//                        if(sysDomain != null){
//                            cmsDomain = Tools.getStr(sysDomain.getSiteDomain());
//                        }
//                    }else{
//                        SysDomain sysDomain = sysDomainMapper.selectById(mailDomain, pyqJob.getMerId());
//                        if(sysDomain != null){
//                            cmsDomain = Tools.getStr(sysDomain.getSiteDomain());
//                        }
//                    }
//
//                    if(StringUtils.isBlank(cmsDomain)){ //官方域名
//                        logger.error("----老林云商品链接生成中间页功能----设备域名未配置---");
//                        return;
//                    }
//
//                    String llyMiddlePageMethod = uzaiConsoleSysConfig.getLlyMiddlePageMethod();
//                    PyqLlyGoods pyqLlyGoods = pyqLlyGoodsMapper.selectById(Long.valueOf(pyqJob.getItemId()));
//
//                    if(pyqLlyGoods == null ){
//                        logger.error("----老林商品库未找到该商品，此商品已经过期或者删除---");
//                        return;
//                    }
//
//                    if(pyqLlyGoods != null){
//                        HashMap<String, List<LlyMiddleDetail>> llyMiddleDetailHashMap = JSONObject.parseObject(pyqLlyGoods.getData(), new TypeReference<HashMap<String, List<LlyMiddleDetail>>>(){});
//                        if(llyMiddleDetailHashMap != null){
//                            //评论内容替换变量
//                            String shortLinkListStr = Tools.getStr(pyqLlyGoods.getShortlink());
//                            if(StringUtils.isNotBlank(shortLinkListStr)){
//                                List<String> shortLinkList = JSONObject.parseArray(shortLinkListStr, String.class);
//                                if(shortLinkList != null){
//                                    for(String shortLink : shortLinkList){
//                                        String middPageUrl = cmsDomain + "/" + llyMiddlePageMethod;
//                                        if(StringUtils.isNotBlank(shortLink) && StringUtils.isNotBlank(middPageUrl)){
//                                            //封装插入到中间页内容
//                                            List<LlyMiddleDetail> llyMiddleDetailList_new = new ArrayList<>();
//                                            //List<LlyMiddleDetail> llyMiddleDetailList = JSONObject.parseArray(pyqLlyGoods.getData(), LlyMiddleDetail.class);
//                                            //从HashMap中获取
//                                            List<LlyMiddleDetail> llyMiddleDetailList = llyMiddleDetailHashMap.get(shortLink);
//                                            if(llyMiddleDetailList != null && llyMiddleDetailList.size() > 0){
//                                                for (LlyMiddleDetail llyMiddleDetail : llyMiddleDetailList){
//                                                    //中间页内容
//                                                    String data_content = llyMiddleDetail.getContent();
//                                                    if(StringUtils.isNotBlank(data_content)){
//                                                        String itemId = llyMiddleDetail.getItemId();
//                                                        String bizSceneId = llyMiddleDetail.getBizSceneId();
//                                                        if(StringUtils.isNotBlank(itemId)){
//                                                            //转链生成新的购买淘口令，保持到老林云商品中间页数据当中
//                                                            TurnlinkDto turnlinkDto = new TurnlinkDto();
//                                                            turnlinkDto.setMerId(pyqJob.getMerId());
//                                                            turnlinkDto.setPlatform(0); //老林云只有淘宝
//                                                            turnlinkDto.setCouponId(pyqJob.getCouponId());
//                                                            turnlinkDto.setDevicePlanId(pyqJob.getDevicePlanId());
//                                                            turnlinkDto.setDeviceUniqueId(deviceUniqueId);
//                                                            turnlinkDto.setItemId(itemId);
//                                                            turnlinkDto.setBizSceneId(bizSceneId);
//                                                            turnlinkDto.setGenerateShortUrl(0);//不生成短链接
//                                                            SimpleTurnlinkVo simpleTurnlinkVo = pyqMaterialService.getGoodInfo(turnlinkDto);
//                                                            String pwd_new = simpleTurnlinkVo.getPurePwd();
//                                                            if(StringUtils.isBlank(pwd_new)){
//                                                                logger.error("----老林云商品链接生成中间页功能----淘口令为空---");
//                                                                return;
//                                                            }else{
//                                                                String data_content_new = data_content.replace(itemId, pwd_new);
//                                                                llyMiddleDetail.setContent(data_content_new);
//                                                                llyMiddleDetail.setPwd(pwd_new);
//                                                            }
//                                                        }
//                                                    }
//                                                    llyMiddleDetailList_new.add(llyMiddleDetail);
//                                                }
//                                            }
//
//                                            String data_new = JSONObject.toJSONString(llyMiddleDetailList_new);
//                                            Long id = IdWorker.getId();
//                                            middPageUrl = middPageUrl + id;
//                                            //生成短链接
//                                            GenerateShortUrlDto generateShortUrlDto = new GenerateShortUrlDto();
//                                            generateShortUrlDto.setMerId(pyqJob.getMerId());
//                                            generateShortUrlDto.setUrl(middPageUrl);
//                                            UzaiRespVo<String> uzaiRespVo = uzaiTurnlinkFeignService.generateShortUrl(generateShortUrlDto);
//                                            logger.info("---老林云商品生成中间页生成短链接---dto={},result={}",JSONObject.toJSONString(generateShortUrlDto), JSONObject.toJSONString(uzaiRespVo));
//                                            if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
//                                                //获取生成的短链接
//                                                middPageUrl = uzaiRespVo.getData();
//                                                //短链接为空，则不发朋友圈
//                                                if(StringUtils.isBlank(middPageUrl)){
//                                                    //再次请求一次，防止第一次请求失败
//                                                    UzaiRespVo<String> uzaiRespVo_repeat = uzaiTurnlinkFeignService.generateShortUrl(generateShortUrlDto);
//                                                    logger.info("---老林云商品生成中间页生成短链接-第一次失败，第二次请求调用----dto={},result={}",JSONObject.toJSONString(generateShortUrlDto), JSONObject.toJSONString(uzaiRespVo_repeat));
//                                                    if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200){
//                                                        //获取生成的短链接
//                                                        middPageUrl = uzaiRespVo_repeat.getData();
//                                                        //短链接为空，则不发朋友圈
//                                                        if(StringUtils.isBlank(middPageUrl)){
//                                                            logger.error("----老林云商品链接生成中间页功能----短链接为空---");
//                                                            return;
//                                                        }
//                                                    }
//                                                }
//                                            }
//
//                                            //保持老林云商品中间页链接
//                                            PyqLlyShortlink pyqLlyShortlink = new PyqLlyShortlink();
//                                            pyqLlyShortlink.setId(id);
//                                            pyqLlyShortlink.setGoodsid(pyqLlyGoods.getId());
//                                            pyqLlyShortlink.setData(data_new);
//                                            pyqLlyShortlink.setCreateTime(now);
//                                            pyqLlyShortlink.setUpdateTime(now);
//                                            pyqLlyShortlink.setUrl(middPageUrl);
//                                            pyqLlyShortlinkMapper.insertSelective(pyqLlyShortlink);
//
//                                            commentContent = commentContent.replace(shortLink, middPageUrl);
//                                            pyqJobDetail.setCommentContent(commentContent);
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
        }

        return pyqJobDetail;
    }

    /**
     * 批量再发一次
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailIdListDto
     * @return null
     */
    public void batchSendBegin(PyqJobDetailIdListDto pyqJobDetailIdListDto){

        List<String> idList = pyqJobDetailIdListDto.getIdList();

        if(pyqJobDetailIdListDto.getIdList() == null || pyqJobDetailIdListDto.getIdList().size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择明细id列表");
        }

        for(String id : idList){
            try {
                PyqJobDetailIdDto pyqJobDetailIdDto = new PyqJobDetailIdDto();
                BeanUtils.copyProperties(pyqJobDetailIdListDto, pyqJobDetailIdDto);
                pyqJobDetailIdDto.setMerId(pyqJobDetailIdListDto.getMerId());
                pyqJobDetailIdDto.setId(id);
                sendBegin(pyqJobDetailIdDto);
            }catch (Exception e){

            }
        }
    }

    /**
     * 批量删除微信朋友圈-不删明细
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailDeleteListDto
     * @return null
     */
    public void batchDeleteWxPyq(PyqJobDetailDeleteListDto pyqJobDetailDeleteListDto){

        List<PyqJobDetailDeleteDto> pyqJobDetailDeleteDtoList = pyqJobDetailDeleteListDto.getPyqJobDetailDeleteDtoList();

        if(pyqJobDetailDeleteDtoList == null || pyqJobDetailDeleteDtoList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择删除的朋友圈列表");
        }

        for(PyqJobDetailDeleteDto pyqJobDetailDeleteDto : pyqJobDetailDeleteDtoList){
            try{
                BeanUtils.copyProperties(pyqJobDetailDeleteListDto, pyqJobDetailDeleteDto);
                deleteWxPyq(pyqJobDetailDeleteDto);
            }catch (Exception e){

            }
        }
    }

    /**
     * 查询朋友圈发送数量
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailQuery
     * @return null
     */
    public int findPyqJobDetailCount(PyqJobDetailQuery pyqJobDetailQuery){
        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetailQuery.getMerId());

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //运营商ID
        if(pyqJobDetailQuery.getMerId() != null){
            boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(pyqJobDetailQuery.getMerId())));
        }

        //发送任务id
        if(pyqJobDetailQuery.getJobId() != null){
            boolQuery.must(QueryBuilders.termQuery("jobId",pyqJobDetailQuery.getJobId()));
        }

        //状态
        if(pyqJobDetailQuery.getStatus() != null){
            boolQuery.must(QueryBuilders.termQuery("status",pyqJobDetailQuery.getStatus()));
        }

        //机器人唯一id
        if(pyqJobDetailQuery.getDeviceUniqueId() != null){
            boolQuery.must(QueryBuilders.termQuery("deviceUniqueId",pyqJobDetailQuery.getDeviceUniqueId()));
        }

        if(pyqJobDetailQuery.getComplete() != null){
            if(pyqJobDetailQuery.getComplete().intValue() == 1){ //发送完成
                boolQuery.must(QueryBuilders.rangeQuery("status").gte(3));
            }
        }

        //淘口令尾部
        if(pyqJobDetailQuery.getItemTailId() != null){
            boolQuery.must(QueryBuilders.termQuery("itemTailId.keyword",pyqJobDetailQuery.getItemTailId()));
        }

        //开始时间和结束世界
        if(pyqJobDetailQuery.getQueryStartTime() != null && pyqJobDetailQuery.getQueryEndTime() != null ){
            boolQuery.must(QueryBuilders.rangeQuery("createTime").gte(pyqJobDetailQuery.getQueryStartTime()).lte(pyqJobDetailQuery.getQueryEndTime()));
        }

        searchSourceBuilder.query(boolQuery);

        //打印条件
        //logger.info(searchSourceBuilder.query().toString());

        long count =   elasticsearchUtilGroupMsg.searchTotal(uzai_pyq_job_detail, searchSourceBuilder);

        return (int)count;
    }

    /**
     * 获取商品信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param turnlinkDto
     * @return null
     */
    private SimpleTurnlinkVo getGoodInfo(TurnlinkDto turnlinkDto){
        SimpleTurnlinkVo simpleTurnlinkVo = new SimpleTurnlinkVo();
        if(turnlinkDto.getPlatform() == null){
            logger.info("请选择平台");
            simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
            simpleTurnlinkVo.setReturnMsg("请选择平台");
            return simpleTurnlinkVo;
        }

        if(turnlinkDto.getDevicePlanId() == null){
            logger.info("请选择设备方案");
            simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
            simpleTurnlinkVo.setReturnMsg("请选择设备方案");
            return simpleTurnlinkVo;
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(turnlinkDto.getDevicePlanId(), turnlinkDto.getMerId());

        if(pyqDevicePlan == null){
            logger.info("该设备方案不存在");
            simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
            simpleTurnlinkVo.setReturnMsg("该设备方案不存在");
            return simpleTurnlinkVo;
        }

        Long deviceUniqueId = turnlinkDto.getDeviceUniqueId();
        Long tbTokenId = null;
        String pid = "";
        Long jdTokenId = null;
        Long pddTokenId = null;
        Long vphTokenId = null;
        Long dyTokenId = null;
        Long ksTokenId = null;
        Integer pddTokenType = null;
        Integer dyTokenType = null;
        Integer ksTokenType = null;
        Integer jdTokenType = null;
        Integer vphTokenType = null;

        //默认机器人为空，则未指定，则指定配置方案中的默认第一个机器人
        if(deviceUniqueId == null){
            //发送朋友圈的机器人列表
            List<Long> deviceUniqueIdList = null;
            if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
                //验证发送机器人
                deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
            }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
                DeviceQuery deviceQuery = new DeviceQuery();
                deviceQuery.setMerId(turnlinkDto.getMerId());
                deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
                Page<Device> page = deviceService.findDevicePage(deviceQuery);
                if(page != null && page.getRecords() != null && page.getRecords().size() > 0){
                    deviceUniqueIdList = new ArrayList<>();
                    for (Device device : page.getRecords()){
                        deviceUniqueIdList.add(device.getId());
                    }
                }
            }
            if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
                logger.info("该设备方案未选择机器人");
                simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
                simpleTurnlinkVo.setReturnMsg("该设备方案未选择机器人");
                return simpleTurnlinkVo;
            }
            deviceUniqueId = deviceUniqueIdList.get(0);
        }

        //查询机器人信息
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, pyqDevicePlan.getDeviceType(), turnlinkDto.getMerId());
        if(device == null ){
            logger.info("请求商品转链-机器人id为空");
            simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
            simpleTurnlinkVo.setReturnMsg("请求商品转链-机器人id为空");
            return simpleTurnlinkVo;
        }

        if(pyqDevicePlan.getTokenType() != null && pyqDevicePlan.getTokenType().intValue() == 1){ //自己设置联盟
            JSONObject jsonObjectToken = JSONObject.parseObject(pyqDevicePlan.getTokenInfo());
            if(jsonObjectToken != null){
                //淘宝token
                JSONObject tbTokenJsonObject  = jsonObjectToken.getJSONObject("tbToken");
                if(tbTokenJsonObject != null){
                    tbTokenId = tbTokenJsonObject.getLong("tokenId");
                    pid = tbTokenJsonObject.getString("pid");
                }
                //京东token
                JSONObject jdTokenJsonObject  = jsonObjectToken.getJSONObject("jdToken");
                if(jdTokenJsonObject != null){
                    jdTokenId = jdTokenJsonObject.getLong("tokenId");
                    jdTokenType = jdTokenJsonObject.getInteger("type");
                }
                //拼多多token
                JSONObject pddTokenJsonObject  = jsonObjectToken.getJSONObject("pddToken");
                if(pddTokenJsonObject != null){
                    pddTokenId = pddTokenJsonObject.getLong("tokenId");
                    pddTokenType = pddTokenJsonObject.getInteger("type");
                }
                //唯品会token
                JSONObject vphTokenJsonObject  = jsonObjectToken.getJSONObject("vphToken");
                if(vphTokenJsonObject != null){
                    vphTokenId = vphTokenJsonObject.getLong("tokenId");
                    vphTokenType = vphTokenJsonObject.getInteger("type");
                }
                //抖音token
                JSONObject dyTokenJsonObject  = jsonObjectToken.getJSONObject("dyToken");
                if(dyTokenJsonObject != null){
                    dyTokenId = dyTokenJsonObject.getLong("tokenId");
                    dyTokenType = dyTokenJsonObject.getInteger("type");
                }
                //快手token
                JSONObject ksTokenJsonObject  = jsonObjectToken.getJSONObject("ksToken");
                if(ksTokenJsonObject != null){
                    ksTokenId = ksTokenJsonObject.getLong("tokenId");
                    ksTokenType = ksTokenJsonObject.getInteger("type");
                }
            }
        }else{ //默认从机器人中获取
            ConfigPlan configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
            if(configPlan != null){
                //淘宝token-淘宝目前不从配置方案中获取,淘宝商品转链采用导购联盟
                if(false){
                    JSONObject jsonObject_tb = JSONObject.parseObject(configPlan.getTbAccountId());
                    if(jsonObject_tb != null) {
                        JSONArray jsonArray = jsonObject_tb.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                tbTokenId = tokenList.get(0);
                                TbToken tbToken = tbTokenMapper.selectById(tbTokenId, turnlinkDto.getMerId());
                                if (tbToken != null) {
                                    pid = tbToken.getDefPid();
                                }
                            }
                        }
                    }
                }

                //京东token
                JSONObject jsonObject_jd = null;
                jdTokenType = configPlan.getJdAccountType();
                if(jdTokenType != null && jdTokenType.intValue() == 1){ //推老板共享联盟
                    jsonObject_jd = JSONObject.parseObject(configPlan.getTlbJdAccountId());
                }else{ //拼多多联盟
                    jsonObject_jd = JSONObject.parseObject(configPlan.getJdAccountId());
                }
                if(jsonObject_jd != null) {
                    JSONArray jsonArray = jsonObject_jd.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            jdTokenId = tokenList.get(0);
                        }
                    }
                }

                //唯品会token
                JSONObject jsonObject_vph = null;
                vphTokenType = configPlan.getVphAccountType();
                if(vphTokenType != null && vphTokenType.intValue() == 1){ //推老板共享联盟
                    jsonObject_vph = JSONObject.parseObject(configPlan.getTlbVphAccountId());
                }else{ //拼多多联盟
                    jsonObject_vph = JSONObject.parseObject(configPlan.getVphAccountId());
                }
                if(jsonObject_vph != null) {
                    JSONArray jsonArray = jsonObject_vph.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            vphTokenId = tokenList.get(0);
                        }
                    }
                }

                //拼多多token
                JSONObject jsonObject_pdd = null;
                pddTokenType = configPlan.getPddAccountType();
                if(configPlan.getPddAccountType() != null && configPlan.getPddAccountType().intValue() == 1){ //推老板共享联盟
                    jsonObject_pdd = JSONObject.parseObject(configPlan.getTlbPddAccountId());
                }else{ //拼多多联盟
                    jsonObject_pdd = JSONObject.parseObject(configPlan.getPddAccountId());
                }
                if(jsonObject_pdd != null) {
                    JSONArray jsonArray = jsonObject_pdd.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            pddTokenId = tokenList.get(0);
                        }
                    }
                }

                //抖音token
                JSONObject jsonObject_dy = null;
                dyTokenType = configPlan.getDyAccountType();
                if(configPlan.getDyAccountType() != null && configPlan.getDyAccountType().intValue() == 1){ //推老板共享联盟
                    jsonObject_dy = JSONObject.parseObject(configPlan.getTlbDyAccountId());
                }else{ //拼多多联盟
                    jsonObject_dy = JSONObject.parseObject(configPlan.getDyAccountId());
                }
                if(jsonObject_dy != null) {
                    JSONArray jsonArray = jsonObject_dy.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            dyTokenId = tokenList.get(0);
                        }
                    }
                }

                //抖音token
                JSONObject jsonObject_ks = null;
                ksTokenType = configPlan.getKsAccountType();
                if(configPlan.getKsAccountType() != null && configPlan.getKsAccountType().intValue() == 1){ //推老板共享联盟
                    jsonObject_ks = JSONObject.parseObject(configPlan.getTlbKsAccountId());
                }else{ //快手联盟
                    jsonObject_ks = JSONObject.parseObject(configPlan.getKsAccountId());
                }
                if(jsonObject_ks != null) {
                    JSONArray jsonArray = jsonObject_ks.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            ksTokenId = tokenList.get(0);
                        }
                    }
                }
            }
        }

        if(StringUtils.isBlank(turnlinkDto.getItemId())){
            simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
            simpleTurnlinkVo.setReturnMsg("缺少商品链接、商品id、淘口令、抖音口令、快口令等信息");
            return simpleTurnlinkVo;
        }

        SimpleTurnLinkDto simpleTurnLinkDto = new  SimpleTurnLinkDto();
        if(StringUtils.isNotBlank(turnlinkDto.getUrl())){
            simpleTurnLinkDto.setUrl(turnlinkDto.getUrl());
        }
        simpleTurnLinkDto.setMerId(turnlinkDto.getMerId());
        simpleTurnLinkDto.setDeviceUniqueId(deviceUniqueId);
        simpleTurnLinkDto.setDeviceType(device.getRecvmsgType());
        simpleTurnLinkDto.setCouponId(turnlinkDto.getCouponId());
        simpleTurnLinkDto.setBizSceneId(turnlinkDto.getBizSceneId());
        simpleTurnLinkDto.setGenerateShortUrl(turnlinkDto.getGenerateShortUrl());
        simpleTurnLinkDto.setMiddlePageDomainId(pyqDevicePlan.getDomain());
        simpleTurnLinkDto.setIgnoreShortUrlAuth(turnlinkDto.getIgnoreShortUrlAuth());
        simpleTurnLinkDto.setChannel(OrderSourceEnum.WECHAT_PYQ.getId());//个人微信朋友圈

        UzaiRespVo<SimpleTurnlinkVo> uzaiRespVo = null;
        if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == turnlinkDto.getPlatform().intValue()){ //淘宝
            if(tbTokenId == null) { //设备方案未配置淘宝联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "", 0L,
                        "朋友圈-设备方案未配置淘宝联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置淘宝联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
                simpleTurnlinkVo.setReturnMsg("设备方案未配置淘宝联盟");
                return simpleTurnlinkVo;
            }else{
                int tbQueryType = RegularUtil.getTbQueryType(turnlinkDto.getItemId());
                if(tbQueryType == 1){
                    simpleTurnLinkDto.setUrl(turnlinkDto.getItemId());
                }else if(tbQueryType == 2){
                    simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                }else if(tbQueryType == 3){
                    simpleTurnLinkDto.setPwd(turnlinkDto.getItemId());
                }else{
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未识别到商品信息");
                }
                simpleTurnLinkDto.setTokenId(tbTokenId);
                simpleTurnLinkDto.setPid(pid);
                uzaiRespVo = uzaiTurnlinkFeignService.tbTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用淘宝转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(PlatformTypeEnum.PT_JD.getId().intValue() == turnlinkDto.getPlatform().intValue()){ //京东

            if(jdTokenId == null){ //发单设备方案未配置京东联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置京东联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置京东联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
                simpleTurnlinkVo.setReturnMsg("设备方案未配置京东联盟");
                return simpleTurnlinkVo;

            }else{
                //判断输入得是商品id还是商品链接
                if(turnlinkDto.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setUrl(turnlinkDto.getItemId());
                }else{
                    simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                }
                simpleTurnLinkDto.setTokenId(jdTokenId);
                simpleTurnLinkDto.setJdTokenType(jdTokenType);
                uzaiRespVo = uzaiTurnlinkFeignService.jdTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用京东转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(PlatformTypeEnum.PT_PDD.getId().intValue() == turnlinkDto.getPlatform().intValue()){ //拼多多
            if(pddTokenId == null){ //发单设备方案未配置拼多多联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置拼多多联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置拼多多联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
                simpleTurnlinkVo.setReturnMsg("设备方案未配置拼多多联盟");
                return simpleTurnlinkVo;
            }else{
                //拼多多商品优先选择商品url进行转链。（商品id进行转链不能参加千万补贴）
                if(StringUtils.isNotBlank(turnlinkDto.getUrl())){
                    simpleTurnLinkDto.setUrl(turnlinkDto.getUrl());
                }else{
                    if(turnlinkDto.getItemId().contains("http")){//商品链接
                        simpleTurnLinkDto.setUrl(turnlinkDto.getItemId());
                    }else{
                        simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                    }
                }

                simpleTurnLinkDto.setTokenId(pddTokenId);
                simpleTurnLinkDto.setPddTokenType(pddTokenType);
                simpleTurnLinkDto.setUseZsUnitUrl(true);
                uzaiRespVo = uzaiTurnlinkFeignService.pddTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用拼多多转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(PlatformTypeEnum.PT_VPH.getId().intValue() == turnlinkDto.getPlatform().intValue()){ //唯品会
            if(vphTokenId == null){ //发单设备方案未配置唯品会联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置唯品会联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置唯品会联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

            }else{
                //判断输入得是商品id还是商品链接
                if(turnlinkDto.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setUrl(turnlinkDto.getItemId());
                }else{
                    simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                }
                simpleTurnLinkDto.setTokenId(vphTokenId);
                simpleTurnLinkDto.setVphTokenType(vphTokenType);
                uzaiRespVo =uzaiTurnlinkFeignService.vphTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用唯品会转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(turnlinkDto.getPlatform().intValue() == 4){//抖音
            if(dyTokenId == null) { //设备方案未配置淘宝联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "", 0L,
                        "朋友圈-设备方案未配置抖音联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置抖音联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
                simpleTurnlinkVo.setReturnMsg("设备方案未配置抖音联盟");
                return simpleTurnlinkVo;
            }else{
                //判断输入得是商品id还是商品链接
                if(turnlinkDto.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setPwd(turnlinkDto.getItemId()); //抖音连接转链参数放pwd参数
                }else{
                    //先判断商品id
                    String itemId = Tools.findTbItemIdByRegex(turnlinkDto.getItemId());
                    if(StringUtils.isNotBlank(itemId)){
                        simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                    }else{
                        //查找淘口令，找到通过淘口令转链
                        String pwd = Tools.findTbPwdByRegex(turnlinkDto.getItemId());
                        if(StringUtils.isNotBlank(pwd)){
                            simpleTurnLinkDto.setPwd(pwd);
                        }else{ //最后则默认为商品id
                            simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                        }
                    }
                }

                simpleTurnLinkDto.setTokenId(dyTokenId);
                simpleTurnLinkDto.setDyTokenType(dyTokenType);
                uzaiRespVo = uzaiTurnlinkFeignService.dyTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用抖音转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(turnlinkDto.getPlatform().intValue() == 5){//快手
            if(ksTokenId == null) { //设备方案未配置快手联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "", 0L,
                        "朋友圈-设备方案未配置抖音联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置快手联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
                simpleTurnlinkVo.setReturnMsg("设备方案未配置快手联盟");
                return simpleTurnlinkVo;
            }else{
                //判断输入得是商品id还是商品链接
                if(turnlinkDto.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setPwd(turnlinkDto.getItemId()); //抖音连接转链参数放pwd参数
                }else{
                    //判断输入得是商品id还是商品链接
                    if(Tools.isInteger(turnlinkDto.getItemId())){
                        simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                    }else{
                        simpleTurnLinkDto.setPwd(turnlinkDto.getItemId());
                    }
                }

                simpleTurnLinkDto.setTokenId(ksTokenId);
                simpleTurnLinkDto.setKsTokenType(ksTokenType);
                uzaiRespVo = uzaiTurnlinkFeignService.ksTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用快手转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }

        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200 && uzaiRespVo.getData() != null){
            simpleTurnlinkVo = uzaiRespVo.getData();
            simpleTurnlinkVo.setReturnCode(uzaiRespVo.getCode());
            simpleTurnlinkVo.setReturnMsg(uzaiRespVo.getMsg());
        }else{
            if(StringUtils.isNotBlank(uzaiRespVo.getMsg())){
                simpleTurnlinkVo.setReturnCode(uzaiRespVo.getCode());
                simpleTurnlinkVo.setReturnMsg(uzaiRespVo.getMsg());
            }else{
                simpleTurnlinkVo.setReturnCode(ResponseCode.BUSINESS_EXCEPTION);
                simpleTurnlinkVo.setReturnMsg("转链微服务接口调用失败");
            }
            return simpleTurnlinkVo;
        }


        return simpleTurnlinkVo;
    }

    /**
     * 批量删除朋友圈明细
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDetailIdListDto
     * @return null
     */
    public void batchDeleteById(PyqJobDetailIdListDto pyqJobDetailIdListDto){

        List<String> idList = pyqJobDetailIdListDto.getIdList();

        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择明细id列表");
        }

        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetailIdListDto.getMerId());

        for(String id : idList){
            try {
                Map<String,Object> pyqJobDetailEsMap = elasticsearchUtilGroupMsg.searchDataById(uzai_pyq_job_detail, id, null);
                PyqJobDetail pyqJobDetail = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pyqJobDetailEsMap)), PyqJobDetail.class);
                if(pyqJobDetail != null && pyqJobDetail.getStatus() != null) {
                    //只能删除未发送或发送失败的朋友圈明细记录
                    if(PyqJobDetailStatusEnum.NOSEND.getValue().intValue() == pyqJobDetail.getStatus().intValue()
                        || PyqJobDetailStatusEnum.SENDFAIL.getValue().intValue() == pyqJobDetail.getStatus().intValue()
                    ){
                        elasticsearchUtilGroupMsg.deleteDataById(uzai_pyq_job_detail, id);
                    }
                }
            }catch (Exception e){

            }
        }
    }

}
